package com.yztstudy.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * Redis的ID生成器
 */


@Component
public class RedisIdWorker {

    private static final long BEGIN_TIMESTAMP = 1678988172L; //开始时间戳
    private static final int COUNT_BITS = 32; //序列号的位数

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix)
    {
        //1.生成时间戳，31位
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC); //当前时间戳
        long timeStamp = nowSecond - BEGIN_TIMESTAMP; //时间戳之差

        //2.生成序列号，32位
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);//自增,每一天的key不一样

        //3.拼接时间戳+序列号
        return (timeStamp << COUNT_BITS) | count;
    }
}
